package com.jiangnan.ui.fragment

import android.content.Intent
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.jiangnan.databinding.FragmentRecoBinding
import com.jiangnan.entity.LoginInfo
import com.jiangnan.ui.activity.ItemAdapterRepositoryActivity
import com.jiangnan.ui.adapter.MaxRepositoryQuickAdapter
import com.jiangnan.ui.adapter.RecommendationAdapter
import com.jiangnan.util.SharedPrefUtil
import com.jiangnan.viewmodel.BookViewModel
import com.jiangnan.viewmodel.RecommendationViewModel


// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = "param2"

/**
 * A simple [Fragment] subclass.
 * Use the [RecoFragment.newInstance] factory method to
 * create an instance of this fragment.
 */
class RecoFragment : Fragment() {
    // TODO: Rename and change types of parameters
    private var param1: String? = null
    private var param2: String? = null
    private lateinit var binding: FragmentRecoBinding
    private lateinit var viewModel: RecommendationViewModel
    private lateinit var bookViewModel: BookViewModel
    private var page: Int? = 1
    private var pageSize: Int? = 15
    private var requestParam: String? = ""
    private var loginInfo : LoginInfo? = null
    private lateinit var adapter: RecommendationAdapter
    private lateinit var maxAdapter: MaxRepositoryQuickAdapter

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate(inflater, com.jiangnan.R.layout.fragment_reco, container, false)
        viewModel = ViewModelProvider(this).get(RecommendationViewModel::class.java)
        bookViewModel = ViewModelProvider(this)[BookViewModel::class.java]
        loginInfo = SharedPrefUtil.getLoginInfo(requireContext())

        adapter = RecommendationAdapter()
        binding.recyclerView.layoutManager = LinearLayoutManager(context)
        binding.recyclerView.adapter = adapter

        adapter.setOnItemClickListener { adapter, view, position ->
            val book = adapter.getItem(position)!!.book
            val intent = Intent(requireContext(), ItemAdapterRepositoryActivity::class.java)
            intent.putExtra("book", book)  // 传递 Book 对象
            startActivity(intent)
        }



        viewModel = ViewModelProvider(this).get(RecommendationViewModel::class.java)
        viewModel.recommendations.observe(viewLifecycleOwner) { recommendations ->
            adapter.submitList(recommendations)
        }

        // 例如，假设用户 ID 为 1
        viewModel.fetchRecommendations(loginInfo!!.id, topN = 10)

        initRefreshLayout()
        val recyclerView = binding.recyclerViewH
        recyclerView.layoutManager = StaggeredGridLayoutManager(
            1,
            StaggeredGridLayoutManager.HORIZONTAL
        )
        maxAdapter = MaxRepositoryQuickAdapter()
        recyclerView.adapter = maxAdapter

        maxAdapter.setOnItemClickListener { adapter, view, position ->
            val book = adapter.getItem(position)
            val intent = Intent(requireContext(), ItemAdapterRepositoryActivity::class.java)
            intent.putExtra("book", book)  // 传递 Book 对象
            startActivity(intent)
        }


        bookViewModel.getAllBooksOrderByBorrowNum(page, pageSize, requestParam)
        bookViewModel.bookList.observe(viewLifecycleOwner){
            maxAdapter.submitList(it)
        }

        return binding.root
    }

    private fun initRefreshLayout() {
//        val refreshLayout = binding.refreshLayout as RefreshLayout
//        refreshLayout.setRefreshHeader(ClassicsHeader(context))
//        refreshLayout.setRefreshFooter(ClassicsFooter(context))
//        refreshLayout.setOnRefreshListener { refreshlayout ->
//            refreshlayout.finishRefresh(2000 /*,false*/) //传入false表示刷新失败
//        }
//        refreshLayout.setOnLoadMoreListener { refreshlayout ->
//            refreshlayout.finishLoadMore(2000 /*,false*/) //传入false表示加载失败
//        }
    }


    companion object {
        /**
         * Use this factory method to create a new instance of
         * this fragment using the provided parameters.
         *
         * @param param1 Parameter 1.
         * @param param2 Parameter 2.
         * @return A new instance of fragment RecoFragment.
         */
        // TODO: Rename and change types and number of parameters
        @JvmStatic
        fun newInstance(param1: String, param2: String) =
            RecoFragment().apply {
                arguments = Bundle().apply {
                    putString(ARG_PARAM1, param1)
                    putString(ARG_PARAM2, param2)
                }
            }
    }
}